<?php
/** -------------------------- Class UploadFile 0.1 -----------------------------
 * Project:		FileUpload (Upload File Handler)
 * File:		dpf/fileupload.php
 * Created:		6/19/2005 2:58:34 PM
 * Modified:	6/22/2005 2:58:59 AM
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 * @copyright 2007
 * @author
 * @package DeepFrame::UploadFile
 * @version 0.1
 *
 * ---------------------------------------------------------- */

define("UPLOADFILE_VERSION","0.1");

class FileUpload
{
	var $FILEDIR;
	var $size;
	var $name;
	var $type;
	var $maxsize;

	function handleupload()
	{
		$i = 0;
		if (is_uploaded_file($_FILES['userfile']['tmp_name']))
		{
			$file = $_FILES['userfile'];

			$arr_search = array(
				"/[ \+\=\/\\\:\*\?\"\|\<\>\$\&\%\@\{\}\~\!\#\^\[\]]/",
				"/%20/",
			);

			// amankan nama filenya
			$file['name'] = preg_replace($arr_search, "_", $file['name']);

            // normalisasi direktorinya
			if( (strlen($this->FILEDIR)>0) && ($this->FILEDIR[strlen($this->FILEDIR)-1] != "/") )
				$this->FILEDIR .= '/';

			if(strpos($file['name'],'.') !== false)
			{
				$bits = explode('.',$file['name']);
				$ext = array_pop($bits);
				while(file_exists($this->FILEDIR . implode('.', $bits).($i?'_'.$i:'').'.'.$ext))
				{
					++$i;
					$file['name'] = implode('.',$bits).($i?'_'.$i:'').'.'.$ext;
				}

			//if the filename already exists, append _copy_x (no extension)
			}
			else
			{
				while(file_exists($this->FILEDIR . $file['name'].($i ?'_'.$i:'')))
				{
					++$i;
					$file['name'] = $file['name'].($i?'_'.$i:'');
				}
			}

			// jika beres semua, salin di tujuan yang benar
			if (!@copy($_FILES['userfile']['tmp_name'], $this->FILEDIR . $file['name']))
			{
				return false;
			}
			else
			{
				$this->name = $file['name'];
				$this->size = $file['size'];
				$this->type = $file['type'];

				return true;
			}
		}
	}

	function FileUpload()
	{
		global $DIR_ROOT;
		$this->FILEDIR = $DIR_ROOT;
    }
}
?>